package com.example.finalassessment.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.finalassessment.model.Product;
import com.example.finalassessment.service.IProductService;
import com.example.finalassessment.util.ExceptionCodeMsgEnum;
import com.example.finalassessment.util.ResponseData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author funny_chao
 * @since 2024-12-09
 */
@RestController
@RequestMapping("/product")
public class ProductController {
    @Autowired
    private IProductService productService;


    // 获取分页商品列表
    @GetMapping("/all")
    public ResponseEntity<ResponseData> getAllProducts(
            @RequestParam(value = "page", defaultValue = "1") Integer page,
            @RequestParam(value = "size", defaultValue = "5") Integer size) {

        // 创建 Page 对象，设置当前页和每页显示的数量
        Page<Product> productPage = new Page<>(page, size);

        // 查询分页数据
        Page<Product> resultPage = productService.page(productPage);

        // 返回分页数据
        return ResponseEntity.ok(ResponseData.success(resultPage));
    }


    // 根据ID获取商品
    @GetMapping("/id/{id}")
    public ResponseData getProductById(@PathVariable Integer id) {
        Product product = productService.getById(id); // 获取商品数据
        if (product == null) {
            return ResponseData.error(ExceptionCodeMsgEnum.PRODUCT_NOT_FOUND); // 商品未找到，返回错误响应
        }
        return ResponseData.success(product); // 返回商品数据
    }


    // 添加新商品
    @PostMapping("/add")
    public ResponseEntity<ResponseData> addProduct(@RequestBody Product product) {
        ResponseData responseData = productService.addProduct(product);  // 调用服务层方法添加商品
        return ResponseEntity.ok(responseData);  // 返回响应数据
    }

    // 更新商品信息
    @PostMapping("/edit/{id}")
    public ResponseData updateProduct(@PathVariable Integer id, @RequestBody Product product) {
        product.setId(id);
        return productService.editProduct(id,product);
    }

    // 删除商品
    @DeleteMapping("/delete/{id}")
    public ResponseData deleteProduct(@PathVariable Integer id) {
        return productService.deleteProductById(id);
    }

}
